package com.znsb.msfq.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mobstat.StatService;
import com.znsb.msfq.BaseActivity;
import com.znsb.msfq.R;
import com.znsb.msfq.app.ZnsbApp;
import com.znsb.msfq.utils.ActivityUtil;
import com.znsb.msfq.utils.ErrorCodeUtils;
import com.znsb.msfq.utils.HttpUtils;
import com.znsb.msfq.utils.ImageLoader;
import com.znsb.msfq.utils.IntentUtils;
import com.znsb.msfq.utils.JsonResult;
import com.znsb.msfq.utils.LogUtils;
import com.znsb.msfq.utils.NetworkAddress;
import com.znsb.msfq.utils.OverallData;
import com.znsb.msfq.utils.ResponseUtils;
import com.znsb.msfq.utils.SPUtils;
import com.znsb.msfq.utils.StringUtils;
import com.znsb.msfq.utils.ToastUtils;
import com.znsb.msfq.utils.URLImageParser;
import com.znsb.msfq.view.bgabanner.BGABanner;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @name： 商品详情
 * @author： 杨 广
 * @phone： 17382373271
 * @createTime： 2017/2/8
 * @modifyTime： 2017/2/8
 * @explain：
 */

public class CommodityDetailsActivity extends BaseActivity {

    @Bind(R.id.cda_banner)
    BGABanner cdaBanner;
    @Bind(R.id.cda_tv_freight)
    TextView cdaTvFreight;//运费
    @Bind(R.id.cda_tv_ichtext)
    TextView cdaTvIchtext;//图文文本
    @Bind(R.id.cda_tv_thumbsup)
    CheckBox cdaTvThumbsup;//点赞
    @Bind(R.id.cda_tv_tcollection)
    CheckBox cdaTvTcollection;//收藏
    @Bind(R.id.cda_tv_sun)
    TextView cdaTvSun;//晒单
    @Bind(R.id.cda_tv_directlink)
    TextView cdaTvDirectlink;//直达链接
    @Bind(R.id.title_text)
    TextView titleText;
    @Bind(R.id.cda_tv_into)
    TextView cdaTvInto;//简介
    @Bind(R.id.cda_tv_pice)
    TextView cdaTvPice;//单价
    @Bind(R.id.cda_iv_sloge)
    ImageView cdaIvSloge;//来源图片
    @Bind(R.id.cda_tv_lytext)
    TextView cdaTvLytext;//来源文字
    @Bind(R.id.cda_tv_lregion)
    TextView cdaTvLregion;//区域

    private int id;//商品Id
    private String title;//名称
    private String sourceId;//商品来源ID
    private String sourceName;//商品来源名称
    private String sourceLogo;//商品来源logo
    private String price;//单价
    private String freight;//运费
    private String region;//发货区域
    private String information;//商品介绍，大文本
    private String link;//商品外部链接
    private int isLike;//是否点赞，0未点赞，1已点赞
    private int isCollect;//是否收藏，0未收藏，1已收藏
    private int isComment;//是否晒单，0未晒单，1已晒单

    private List<String> banners;
    //商品图片，图片对象

    private Handler hander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 300:
                    setHeaderBanners(banners, null);
                    SetText();
                    cdaTvThumbsup.setEnabled(true);
                    cdaTvTcollection.setEnabled(true);
                    OverallData.setReload(isComment);
                    if (isLike == 0) {
                        cdaTvThumbsup.setChecked(false);
                    } else if (isLike == 1) {
                        cdaTvThumbsup.setChecked(true);
                    }
                    if (isCollect == 0) {
                        cdaTvTcollection.setChecked(false);
                    } else if (isCollect == 1) {
                        cdaTvTcollection.setChecked(true);
                    }
                    break;
                case 400:
                    if (isLike == 0) {
                        cdaTvThumbsup.setChecked(false);
                    } else if (isLike == 1) {
                        cdaTvThumbsup.setChecked(true);
                    }
                    break;
                case 500:
                    if (isCollect == 0) {
                        cdaTvTcollection.setChecked(false);
                    } else if (isCollect == 1) {
                        cdaTvTcollection.setChecked(true);
                    }
                    break;
            }

        }
    };


    @Override
    protected int getlayoutView() {
        return R.layout.act_commoditydetails;
    }

    @Override
    protected void initView(View view) {
        titleText.setText("商品详情");
    }

    @Override
    protected void initData() {
        banners = new ArrayList<>();
        id = getIntent().getIntExtra("ids", 0);
        GetDetail(id);

    }


    private void SetText() {
        cdaTvInto.setText(title);
        cdaTvPice.setText(price);
        cdaTvLytext.setText(sourceName);
        cdaTvInto.setText(title);
        cdaTvFreight.setText(freight);
        cdaTvLregion.setText(region);
        ImageLoader.imageCircleLoder(cdaIvSloge, sourceLogo);

        URLImageParser urlImgParser = new URLImageParser(cdaTvIchtext, this);
        cdaTvIchtext.setMovementMethod(ScrollingMovementMethod.getInstance());// 设置可滚动
        cdaTvIchtext.setMovementMethod(LinkMovementMethod.getInstance());//设置超链接可以打开网页
        cdaTvIchtext.setText(Html.fromHtml(information, urlImgParser, null));
    }

    public void setHeaderBanners(final List<String> banners, final List<String> imgweburl) {
        if (banners.size() < 1) {
            return;
        }
        cdaBanner.setData(banners, null);
        cdaBanner.setAdapter(new BGABanner.Adapter() {
            @Override
            public void fillBannerItem(BGABanner banner, View view, Object model, int position) {
                ImageLoader.imageLoderNo((ImageView) view, "" + banners.get(position));
            }
        });
    }


    //商品详情
    public void GetDetail(int ids) {

        Map<String, Object> maps = new HashMap<>();
        maps.put("id", ids);//第几页，不传递默认第一页
        HttpUtils.getInstance(CommodityDetailsActivity.this).postAsnyRequest(NetworkAddress.Detail, HttpUtils.getMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                try {
                    LogUtils.i("", ">>>>>>GetDetail" + request);
                    title = JsonResult.getString(request, "title");
                    sourceId = JsonResult.getString(request, "sourceId");
                    sourceName = JsonResult.getString(request, "sourceName");
                    sourceLogo = JsonResult.getString(request, "sourceLogo");
                    freight = "运费：" + JsonResult.getString(request, "freight");
                    region = "有效地区：" + JsonResult.getString(request, "region");
                    link = JsonResult.getString(request, "link");
                    price = "¥" + JsonResult.getString(request, "price");
                    information = JsonResult.getString(request, "information");
                    isLike = JsonResult.getInt(request, "isLike");
                    isCollect = JsonResult.getInt(request, "isCollect");
                    isComment = JsonResult.getInt(request, "isComment");
                    JSONArray imageslist = JsonResult.getJSONArray(request, "images");
                    for (int i = 0; i < imageslist.length(); i++) {
                        JSONObject object = imageslist.getJSONObject(i);
                        banners.add(JsonResult.getString(object, "url"));
                    }
                } catch (Exception e) {
                    LogUtils.i("", ">>>>>>e" + e);
                }
                hander.sendEmptyMessage(300);
            }

            @Override
            public void onFailure(String result) {
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });
    }

    //是否点赞
    public void isLike() {
        LogUtils.i("", ">>>>>>isLike" + isLike);
        Map<String, Object> maps = new HashMap<>();
        maps.put("goodsId", id);//商品ID
        maps.put("type", isLike);//类型，0点赞，1取消点赞
        HttpUtils.getInstance(this).postAsnyRequest(NetworkAddress.isLike, HttpUtils.getLoginMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                LogUtils.i("", ">>>>>>isLikes" + isLike + code + "SSSS" + request);
                if (isLike == 0) {
                    isLike = 1;
                } else {
                    isLike = 0;
                }

            }

            @Override
            public void onFailure(String result) {

                hander.sendEmptyMessage(400);
                LogUtils.i("", ">>>>>>onFailure" + result);
            }
        });
    }

    //是否收藏
    public void isCollect() {

        Map<String, Object> maps = new HashMap<>();
        maps.put("goodsId", id);//商品ID
        maps.put("type", isCollect);//类型，0收藏，1取消收藏
        HttpUtils.getInstance(this).postAsnyRequest(NetworkAddress.isCollect, HttpUtils.getLoginMaps(maps), new ResponseUtils() {
            @Override
            public void onSucceed(String code, JSONObject request) {
                LogUtils.i("", ">>>>>>isCollect" + request);
                if (code.equals(ErrorCodeUtils.code1)) {
                    if (isCollect == 0) {
                        isCollect = 1;
                    } else {
                        isCollect = 0;
                    }

                }

            }

            @Override
            public void onFailure(String result) {

                LogUtils.i("", ">>>>>>onFailure" + result);
                hander.sendEmptyMessage(500);
            }
        });
    }


    @Override
    protected void clickListener(View view) {

    }


    @OnClick({R.id.title_back, R.id.cda_tv_thumbsup, R.id.cda_tv_tcollection, R.id.cda_tv_sun, R.id.cda_tv_directlink})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back://返回
                ActivityUtil.goBack(CommodityDetailsActivity.this);
                break;
            case R.id.cda_tv_thumbsup://点赞
                if (SPUtils.getIsLogin()) {
                    isLike();
                } else {
                    hander.sendEmptyMessage(400);
                    ToastUtils.TextToast(CommodityDetailsActivity.this, this.getResources().getString(R.string.unlogin), 3000);
                }

                break;
            case R.id.cda_tv_tcollection://收藏
                if (SPUtils.getIsLogin()) {
                    isCollect();
                } else {
                    hander.sendEmptyMessage(500);
                    ToastUtils.TextToast(CommodityDetailsActivity.this, this.getResources().getString(R.string.unlogin), 3000);
                }

                break;
            case R.id.cda_tv_sun://晒单
                if (SPUtils.getIsLogin()) {
                    LogUtils.i("",">>>>OverallData.getReload()"+OverallData.getReload());
                    if (OverallData.getReload() == 0) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("ids", id + "");
                        IntentUtils.startActivityAnimGeneral(this, AddShowBillActivity.class, map);
                    } else {
                        ToastUtils.TextToast(CommodityDetailsActivity.this, this.getResources().getString(R.string.noComment), 3000);
                    }
                } else {
                    ToastUtils.TextToast(CommodityDetailsActivity.this, this.getResources().getString(R.string.unlogin), 3000);
                }

                break;
            case R.id.cda_tv_directlink://直达链接
                if (SPUtils.getIsLogin()) {
                    if (StringUtils.isNotNull(link)) {
                        StatService.onEvent(this, "disanfang", "pass", 1);
                        Bundle bundle = new Bundle();
                        bundle.putString("url", link);
                        ActivityUtil.next(CommodityDetailsActivity.this, WebViewActivity.class, bundle);
                    }
                } else {
                    ToastUtils.TextToast(CommodityDetailsActivity.this, this.getResources().getString(R.string.unlogin), 3000);
                }

                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
